# -*- coding: utf-8 -*-

#    Copyright (C) 2015 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import ConfigParser
import hashlib
import gettext
import datetime,time
import locale
from jinja2 import Template
import simplejson as json
import Environment
from dao.User import User
from dao import DaoUtils
#from dao.Language import Language
from dao.Ente import Ente
#from dao.Setconf import SetConf
from web_lib.webutils import *
from lib import utils
from web_lib.session import Session

COOKIENAME = "odcollect"


class Page(object):

    def __init__(self, req):
        self.req = req
        self.path = req.environ['PATH_INFO'].split('/')
        self.auth = Session(req).control()
        self.nameuser = getUsernameFromId(req)
        self.role = getRoleFromId(req)
        self.us = None
        self.vetrina = None
        #self.language= Language().select()
        jinja_env.globals['req'] = req
        jinja_env.globals['conf'] = Environment
        jinja_env.globals['utils'] = utils
        jinja_env.globals['leggiInSessione'] = leggiInSessione
        jinja_env.globals['daoutils'] = DaoUtils
        self.schemaa = leggiInSessione(req, sezione="Main", chiave="schema")
        #print "SCHEMA MANDATO ALLA PAGINA", str(schemaa)
        if not self.schemaa or self.schemaa == "None":
            schemaa = None
        jinja_env.globals['schemaa'] = self.schemaa

    def template_loaded(self, template, req=None):
        _ = self.setlang()
        template.filters.insert(0, Translator(_))

    def getLang(self, req):
        """
        Funzione che comanda la lingua
        """
        return "it"

    def setlang(self):
        languages = self.getLang(self.req)
        try:
            lang = gettext.translation('messages', Environment.configPath+'lang',languages=[languages] )
        except:
            lang = gettext.translation('messages', Environment.configPath+'lang',languages=["it"] )
        _ = lang.ugettext
        lang.install()
        return _

    def tpl(self, req):
        loader = TemplateLoader([Environment.templates_dir],callback=self.template_loaded)
        self.tmpl = loader.load(includeFile(self.req,'index') +'.html')

    def createCookie(self, resp, cookiename, cookieval):
        resp.set_cookie(cookiename, value=cookieval, path='/', domain=None)
        return resp

    def deleteCookie(self, resp, cookiename):
        resp.delete_cookie(cookiename, path='/', domain=None)
        return resp

    def bodyTags(self, pageData):
        if pageData["bodyTags"]:
            for dao in pageData["bodyTags"]:
                for attr in dir(pageData[dao]):
                    if attr[0] !="_" and type(getattr(pageData[dao],attr)) == type(u"ciao"):
                        template = Template(getattr(pageData[dao],attr))
                        boh = template.render(pageData=pageData)
                        try:
                            setattr(pageData[dao], attr, boh)
                        except:
                            pass
        return pageData

    def render(self, pageData, cookiename=None, cookieval=None, cookiedel=None, langflagged = None):
        pageData['auth'] = self.auth
        pageData["user"] = getUserFromId(self.req)
        id_user = getUserFromId(self.req)
        if id_user:
            id_user = id_user.id
        from dao.UtenteEnte import UtenteEnte
        enti = UtenteEnte().select(id_utente=id_user, batchSize=None)
        pageData['role'] = self.role
        if self.role.lower == "admin":
            pageData["enti_nav"]= Ente().select(batchSize=None)
        else:
            en = []
            for a in enti:
                en.append(Ente().getRecord(id=a.id_ente))
            pageData["enti_nav"]= en


        pageData['nameuser'] = self.nameuser
        pageData['dao_pg'] = None
        if leggiInSessione(sezione="Main", chiave="schema") and leggiInSessione(sezione="Main", chiave="id_oper"):
            id_oper = leggiInSessione(sezione="Main", chiave="id_oper")
            #print "IDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD", id_oper
            if id_oper and id_oper != "None" and id_oper != "":
                from dao.Operatore import Operatore
                try:
                    dao_op = Operatore().getRecord(id=int(id_oper))
                    pageData["oper"] = dao_op
                    if not pageData["user"]:
                        pageData["user"] = pageData["oper"]
                        ente = Ente().select(denominazione_breve= leggiInSessione(sezione="Main", chiave="schema"))
                        if ente:
                            pageData["enti_nav"] = ente
                except:
                    id_oper = salvaInSessione(self.req, sezione="Main", chiave="id_oper", valore=None)
                    pageData["oper"] = None
            else:
                pageData["oper"] = None

        else:
            pageData["oper"] = None

        ente = Ente().select(denominazione_breve=leggiInSessione(sezione="Main", chiave="schema"))
        if ente:
            ente = ente[0]
        else:
            ente = None
        if self.schemaa:
            from dao.TipoCategoria import TipoCategoria
            pageData["menus"] =  TipoCategoria().select(usa_in_menu=True, batchSize=None)
        else:
            pageData["menus"] = []
        pageData["ente_def"] = ente
        if "dao" in pageData:
            resp = render_template(pageData["file"],
                                    pageData=pageData,
                                    dao=pageData["dao"])
        else:
            resp = render_template(pageData["file"],pageData=pageData)

        idcookiename = COOKIENAME
        if idcookiename not in self.req.cookies:
            idcookieval = hashlib.sha1(repr(time.time())).hexdigest()
            resp = self.createCookie(resp, idcookiename, idcookieval)
        if cookiename and cookieval:
            resp = self.createCookie(resp, cookiename, cookieval)
        if cookiedel:
            resp = self.deleteCookie(resp, cookiedel)
        return resp

    def redirect(self, url=None, cookiename=None, cookieval=None,
                    cookienamelang=None, cookievallang=None, cookiedel=None):
        subdomain = '/' + self.path[1] + '/'
        if not url:
            if not self.path[1]:
                resp = RedirectResponse("/")
            else:
                resp = RedirectResponse(subdomain)
        else:
            resp = RedirectResponse(url)
        idcookiename =  COOKIENAME
        if idcookiename not in self.req.cookies:
            idcookieval = hashlib.sha1(repr(time.time())).hexdigest()
            resp = self.createCookie(resp, idcookiename, idcookieval)
        if cookiename and cookieval:
            resp = self.createCookie(resp, cookiename, cookieval)
        if cookienamelang and cookievallang:
            resp = self.createCookie(resp, cookienamelang, cookievallang)
        if cookiedel:
            resp = self.deleteCookie(resp, cookiedel)
        return resp
